package Experiment_3;

import java.io.*;  
import java.util.ArrayList;  
import java.util.List;  
  
class Student implements Serializable {  
    private String name;  
    private int age;  
  
    // 构造函数  
    public Student(String name, int age) {  
        this.name = name;  
        this.age = age;  
    }  
  
    // Getter 和 Setter 方法  
    public String getName() {  
        return name;  
    }  
  
    public void setName(String name) {  
        this.name = name;  
    }  
  
    public int getAge() {  
        return age;  
    }  
  
    public void setAge(int age) {  
        this.age = age;  
    }  
  
    // toString 方法，方便输出  
    @Override  
    public String toString() {  
        return "Student{" +  
                "name='" + name + '\'' +  
                ", age=" + age +  
                '}';  
    }  
}  
  
public class StudentDataStorage {  
  
    // 将学生列表写入文件  
    public static void writeStudentsToFile(List<Student> students, String fileName) {  
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {  
            oos.writeObject(students);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
  
    // 从文件读取学生列表并展示  
    public static void readStudentsFromFileAndDisplay(String fileName) {  
        List<Student> students = null;  
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {  
            students = (List<Student>) ois.readObject();  
        } catch (IOException | ClassNotFoundException e) {  
            e.printStackTrace();  
        }  
  
        if (students != null) {  
            for (Student student : students) {  
                System.out.println(student);  
            }  
        }  
    }  
  
    public static void main(String[] args) {  
        // 创建一个学生列表  
        List<Student> students = new ArrayList<>();  
        students.add(new Student("张三", 20));  
        students.add(new Student("李四", 22));  
        students.add(new Student("王五", 19));  
  
        // 将学生列表写入文件  
        String fileName = "students.dat";  
        writeStudentsToFile(students, fileName);  
  
        // 从文件读取并展示学生信息  
        readStudentsFromFileAndDisplay(fileName);  
    }  
}